import { registerApp, startApp, getInstance } from './app'
import { loadAppResource } from './html'
/**
 * 微服务框架
 */
export default class MicServer {
  constructor () {
    this.apps = {}
  }
  // 单利模式，统一调用这个
  static getInstance (opts = {}) {
    console.log('getInstance', opts)
    return new Promise((resolve, reject) => {
      if (!window._MICSERVER) {
        window._MICSERVER = {}
      }
      if (!window._MICSERVER.instance) {
        window._MICSERVER.instance = new MicServer(opts)
        window._MICSERVER.instance._axios = opts._axios
        window._MICSERVER.instance._vue = opts._vue
        window._MICSERVER.instance._cheerio = opts._cheerio
        window._MICSERVER.instance._ReactDOM = opts._ReactDOM
        const appList = opts.appList || []
        appList.forEach(item => {
          registerApp(window._MICSERVER.instance, item)
        })
      }
      resolve(window._MICSERVER.instance)
    })
  }
  /**
   * 注册App，每次添加一个App就调用一次
   */
  registerApp (opts = {}) {
    registerApp(this, opts)
  }
  startApp (opts = {}) {
    return startApp(this, opts)
  }
  // 跳转路由
  pushRouter (opts = {}, cb) {
    console.log('pushRouter', opts)
    // 1. 判断实例（是否需要加载资源）
    const instance = getInstance(this, opts)
    const path = opts.path || ''
    if (instance) {
      // 有实例，跳转
      cb && cb({
        success: true,
        instance: instance
      })
    } else {
      // 无实例 - load资源继续加载
      console.log(`${opts.appName} 无实例，先加载资源`)
      loadAppResource(this, opts.appName, cb)
    }
  }
}
